import { CloseOutlined, PlusOutlined } from '@ant-design/icons';
import {
  Alert,
  AutoComplete,
  Button,
  Card,
  Form,
  FormListFieldData,
  Input,
  Select,
  Typography,
} from 'antd';

interface Props {
  formRef: any;
  oldData: any;
}

const { Text } = Typography;

// 模型配置表单组件
export default (props: Props) => {
  const { formRef, oldData } = props;

  // 单字段表单项样式
  const formItemStyle = {
    marginBottom: 16,
    minWidth: 220,
  };

  // 操作按钮样式
  /**
   * 单个字段表单视图
   */
  const singleFieldFormView = (
    field: FormListFieldData,
    remove?: (index: number | number[]) => void,
  ) => {
    return (
      <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
        <Form.Item
          label="字段名称"
          name={[field.name, 'fieldName']}
          style={formItemStyle}
          labelCol={{ span: 10 }}
          wrapperCol={{ span: 16 }}
          rules={[
            {
              required: true,
              message: '请输入字段名称',
            },
          ]}
        >
          <Input placeholder="请输入字段名称" />
        </Form.Item>
        <Form.Item
          label="描述"
          name={[field.name, 'description']}
          style={formItemStyle}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
        >
          <Input placeholder="请输入描述" />
        </Form.Item>
        <Form.Item
          label="类型"
          name={[field.name, 'type']}
          style={formItemStyle}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          rules={[
            {
              required: true,
              message: '请选择类型',
            },
          ]}
        >
          <Select placeholder="请选择类型">
            <Select.Option value="String">字符串</Select.Option>
            <Select.Option value="boolean">布尔值</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item
          label="默认值"
          name={[field.name, 'defaultValue']}
          style={formItemStyle}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 18 }}
          rules={[
            {
              required: true,
              message: '请输入或选择默认值',
            },
          ]}
          // 将表单中的布尔值转换为字符串供AutoComplete显示
          getValueProps={(value) => ({
            value: typeof value === 'boolean' ? value.toString() : value,
          })}
          // 将用户输入的字符串转换为布尔值保存
          getValueFromEvent={(value) => {
            if (value === 'true') return true;
            if (value === 'false') return false;
            return value; // 保留其他输入情况
          }}
        >
          <AutoComplete
            placeholder="请输入或选择默认值"
            options={[
              { label: '是（true）', value: 'true' },
              { label: '否（false）', value: 'false' },
            ]}
            filterOption={(inputValue, option) =>
              option!.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
            }
          />
        </Form.Item>
        <Form.Item
          label="缩写"
          name={[field.name, 'abbr']}
          style={formItemStyle}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
        >
          <Input placeholder="请输入缩写" />
        </Form.Item>
        {remove && (
          <Button
            type="text"
            danger
            onClick={() => remove(field.name)}
            style={{ alignSelf: 'flex-end', marginBottom: 16 }}
            icon={<CloseOutlined />}
          />
        )}
      </div>
    );
  };

  return (
    <>
      <Alert message="请在提交前删除为空的配置" type="warning" closable />
      <div style={{ marginBottom: 16 }} />
      <Form.List name={['modelConfig', 'models']}>
        {(fields, { add, remove }) => (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
            {fields.map((field) => {
              const modelConfig = formRef?.current?.getFieldsValue()?.modelConfig ??
                oldData?.modelConfig ?? { models: [] };
              const groupKey = modelConfig.models?.[field.name]?.groupKey;

              return (
                <Card
                  key={field.key}
                  size="small"
                  title={
                    <Text strong style={{ color: groupKey ? '#1890ff' : '#666' }}>
                      {groupKey ? '模型分组配置' : '模型配置'}
                    </Text>
                  }
                  style={{ borderRadius: 8 }}
                  extra={
                    <CloseOutlined
                      onClick={() => remove(field.name)}
                      style={{
                        color: '#999',
                        fontSize: 14,
                        // @ts-ignore
                        ':hover': { color: '#ff4d4f' },
                      }}
                    />
                  }
                >
                  {groupKey ? (
                    <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
                      <Form.Item
                        label="分组 Key"
                        name={[field.name, 'groupKey']}
                        style={formItemStyle}
                        labelCol={{ span: 10 }}
                        wrapperCol={{ span: 16 }}
                        rules={[
                          {
                            required: true,
                            message: '请输入分组key',
                          },
                        ]}
                      >
                        <Input placeholder="分组唯一标识" />
                      </Form.Item>
                      <Form.Item
                        label="组名"
                        name={[field.name, 'groupName']}
                        style={formItemStyle}
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                        rules={[
                          {
                            required: true,
                            message: '请输入组名',
                          },
                        ]}
                      >
                        <Input placeholder="显示用组名" />
                      </Form.Item>
                      <Form.Item
                        label="分组类型"
                        name={[field.name, 'type']}
                        style={formItemStyle}
                        labelCol={{ span: 10 }}
                        wrapperCol={{ span: 18 }}
                        rules={[
                          {
                            required: true,
                            message: '请输入分组类型',
                          },
                        ]}
                      >
                        <Input placeholder="分组类型" />
                      </Form.Item>
                      <Form.Item
                        label="条件"
                        name={[field.name, 'condition']}
                        style={formItemStyle}
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                      >
                        <Input placeholder="生效条件" />
                      </Form.Item>
                    </div>
                  ) : (
                    singleFieldFormView(field)
                  )}

                  {groupKey && (
                    <div style={{ marginTop: 24 }}>
                      <Text strong style={{ display: 'block', marginBottom: 16 }}>
                        组内字段配置
                      </Text>
                      <Form.List name={[field.name, 'models']}>
                        {(subFields, subOpt) => (
                          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                            {subFields.map((subField) =>
                              singleFieldFormView(subField, subOpt.remove),
                            )}
                            <Button
                              type="dashed"
                              onClick={() => subOpt.add()}
                              icon={<PlusOutlined />}
                            >
                              添加组内模型配置
                            </Button>
                          </div>
                        )}
                      </Form.List>
                    </div>
                  )}
                </Card>
              );
            })}
            <Button
              type="primary"
              onClick={() => add()}
              icon={<PlusOutlined />}
            >
              添加模型配置
            </Button>
            <Button
              type="dashed"
              onClick={() => add({ groupName: '新分组', groupKey: 'group' })}
              icon={<PlusOutlined />}
            >
              添加分组模型配置
            </Button>
            <div style={{ marginBottom: 16 }} />
          </div>
        )}
      </Form.List>
    </>
  );
};
